//
//  HDWKWebView.m
//  AccountEasy
//
//  Created by mac on 2020/7/27.
//  Copyright © 2020 AccountEasy. All rights reserved.
//

#import "HDWKWebView.h"
#import "NSTimer+Extension.h"
#import "JhDownProgressView.h"
#import "HDHubView.h"

#define AI_STR_DEFAULT(str) [NSString stringWithFormat:@"%@",str]
//方法事件名称定义
#define FUNC_CALL_CALLNATIVE @"haideapp://callNative"
//事件类别
//获取接口支付状态
#define GET_PAY_STATUS @"/toPayStatus"
#define GET_BIND_CARD @"/toCardBindingStatus"
#define BIND_CARD_SUCCESS @"toCardBindingStatus=2"

#define BACK_PAGE_STATUS @"backPageStatus=1"

@interface HDWKWebView()<WKNavigationDelegate, WKScriptMessageHandler>
{
    NSMutableURLRequest *webRequest;
    WKWebViewConfiguration *wkConfig;
    
    NSArray *configArray;
    NSMutableDictionary *headers;
}

@property (nonatomic, copy  )   WKWebView *wkWebView;
@property (nonatomic, copy  )   UIActivityIndicatorView *loadingView;

@property (nonatomic, strong) NSTimer*timer;
@property (nonatomic, assign) NSInteger nCount;
@property (nonatomic, strong) JhDownProgressView *progressView;

@end

@implementation HDWKWebView


- (void)dealloc
{
    [wkConfig.userContentController removeAllUserScripts];
    _wkWebView.navigationDelegate = nil;
}

#pragma -mark init
- (instancetype)initWithConfig:(NSArray *)jsArray frame:(CGRect)frame
{
    self = [super init];
    if (self) {
        self.frame = frame;
        configArray = jsArray;
        headers = [NSMutableDictionary dictionary];
        
        _titleName = @"";
        _url = @"";
        _userAgent = @"";
        wkConfig = [[WKWebViewConfiguration alloc] init];
        _loadingView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        
        [self initWeb:frame];
    }
    return self;
}

- (void)initWeb:(CGRect)frame
{
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    for (NSString *jsName in configArray) {
        [userContentController addScriptMessageHandler:self name:AI_STR_DEFAULT(jsName)];
    }
    wkConfig.userContentController = userContentController;
    _wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height) configuration:wkConfig];
    _wkWebView.navigationDelegate = self;
    [self addSubview:_wkWebView];
    
    _loadingView.center = _wkWebView.center;
    [self addSubview:_loadingView];
}

#pragma -mark setter
- (void)setUserAgent:(NSString *)userAgent
{
    _userAgent = userAgent;
    if (@available(iOS 12.0, *)){
        NSString *baseAgent = [_wkWebView valueForKey:@"applicationNameForUserAgent"];
        NSString *userAgent = [NSString stringWithFormat:@"%@ %@",baseAgent,_userAgent];
        [_wkWebView setValue:userAgent forKey:@"applicationNameForUserAgent"];
    }
    [_wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSString *newUA = [NSString stringWithFormat:@"%@ %@",result,self->_userAgent];
        self->_wkWebView.customUserAgent = newUA;
    }];
}

- (void)setUrl:(NSString *)url
{
    NSString *urlString = [url stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    urlString = [urlString stringByReplacingOccurrencesOfString:@" " withString:@""];
    urlString = [urlString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    urlString = [urlString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    _url = urlString;
}

- (void)setHeaderParams:(NSDictionary *)headerParams
{
    _headerParams = headerParams;
    [headers setValuesForKeysWithDictionary:_headerParams];
}

#pragma mark - webView加载
- (void)startLoadUrl
{
    if (_url && _url.length > 0)
    {
        NSURL *webUrl = [NSURL URLWithString : [_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];;
        webRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20];
        NSArray *headerKeys = headers.allKeys;
        for (NSInteger i=0;i<headerKeys.count;i++) {
            NSString *key = AI_STR_DEFAULT(headerKeys[i]);
            NSString *value = AI_STR_DEFAULT(headers[key]);
            [webRequest setValue:value forHTTPHeaderField:key];
        }
        [_wkWebView loadRequest:webRequest];
    }
}

- (void)wkRefresh
{
    [self startLoadUrl];
}

#pragma mark - WKWebview
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSURL *URL       = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    NSString *urlString = [URL absoluteString];
    
    if ([urlString containsString:BACK_PAGE_STATUS]) {
        [self wkPopViewController];
        return;
    }
    
    HDLog(@": url(%@) scheme(%@)",URL,scheme);
    if ([[URL host] isEqualToString:@"itunes.apple.com"] &&
        [[UIApplication sharedApplication] openURL:navigationAction.request.URL]) {
        // 解决WKwebview 不能跳转appStore问题
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
        
    }else if ([scheme isEqualToString:@"tel"]) {
        // 解决WKwebview H5不能调用拨打电话问题。
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    // 截取字符串  haideapp://callNative/toCardBindingStatus=2
    if ([urlString containsString:FUNC_CALL_CALLNATIVE]) {
        NSURLComponents *urlComponents = [[NSURLComponents alloc] initWithString:urlString];
        NSString *jsonString = urlComponents.query;
        if (jsonString.length > 0) {
            
            return;
        }else
        {
            if([urlString containsString:GET_BIND_CARD]){
                if ([urlString containsString:BIND_CARD_SUCCESS]) {
                    !self.jsActionBlock ?: self.jsActionBlock(BIND_CARD_SUCCESS, nil);
                }else{
                    [Prompt popPromptViewWithMsg:@"开通失败" duration:3];
                    [self wkPopViewController];
                }
            }
            
        }
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [self startLoading];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    [self stopLoding];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    [self stopLoding];
    if(error.code == NSURLErrorCancelled)  {
        return;
    }
    if (error.code == NSURLErrorUnsupportedURL) {
        return;
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [self stopLoding];
    self.titleName = webView.title;
    if (self.isAdaptive != YES) {
        [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '200%'" completionHandler:nil];
    }
    
//    if (self.openVipDic != nil) {
//        NSString *name = [self dictionaryToString:self.openVipDic];
//        NSString *js   = [NSString stringWithFormat:@"initDataByIos('%@')", name];
//        [webView evaluateJavaScript:js completionHandler:^(id _Nullable result, NSError *_Nullable error) {
//            NSLog(@"------------error:%@", [error localizedDescription]);
//        }];
//        
//    }
}

#pragma mark - 加载JS处理
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if (_jsActionBlock) {
        _jsActionBlock(AI_STR_DEFAULT(message.name),message.body);
    }
}

//处理通用Js调用事件
- (BOOL)dealCommonJsMethod:(NSString *)nativeName jsData:(id)jsData{
    
    BOOL deal = YES;
    return deal;
}

-(void)initTimer{
    self.nCount = 0;
    __weak typeof(self) weakSelf = self;
    self.timer =
    [NSTimer zz_scheduledTimerWithTimeInterval:1
                                       repeats:YES
                                         block:^(NSTimer *timer) { [weakSelf countDown]; }];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
-(void)killTimer{
    if(self.timer){
        [self.timer invalidate];
        self.nCount = 0;
        self.timer = nil;
    }
}

-(void)countDown{
    [self.progressView setProgress:self.nCount/30.0];
    if(self.nCount > 30){
        [self killTimer];
        [HDHubView dismiss];
        [Prompt popPromptViewWithMsg:@"没有查询到支付结果" duration:3];
        return;
    }
    if(self.nCount++ %3 ==0){
    }
}

#pragma -mark 方法
- (void)startLoading
{
    [_loadingView startAnimating];
    _loadingView.hidden = NO;
}

- (void)stopLoding
{
    [_loadingView stopAnimating];
    _loadingView.hidden = YES;
}

- (UIViewController *)findViewController
{
    id target=self;
    while (target) {
        target = ((UIResponder *)target).nextResponder;
        if ([target isKindOfClass:[UIViewController class]])
            break;
    }
    return target;
}

- (void)wkPopViewController{
    [[self findViewController].navigationController popViewControllerAnimated:YES];
}

- (void)wkPopRootViewController{
    [[self findViewController].navigationController popToRootViewControllerAnimated:YES];
}

- (void)wkGoWebHistory{
    if ([_wkWebView canGoBack]) {
        [_wkWebView goBack];
    }
    else{
        [self wkPopViewController];
    }
}

-(JhDownProgressView*)progressView{
    if(!_progressView){
        _progressView = [JhDownProgressView showWithStyle:JhStyle_Text];
        _progressView.progressWidth = 2.0;
        _progressView.hidden =YES;
    }
    return _progressView;
}

- (NSString *)dictionaryToString:(NSDictionary *)dic {
    if (!dic || ![dic isKindOfClass:[NSDictionary class]])
        return nil;
    NSError * error  = nil;
    NSData *  data   = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:&error];
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    if (error) {
        return nil;
    }
    return string;
}

@end
